<?php
namespace Home\Controller;

/**
 * NovelController
 * 小说信息
 */
class NovelController extends CommonController {
    /**
     * 小说列表
     * @return
     */
    public function index() {
        $rank_id = I('get.rank_id');
        if($rank_id){
            $rank_novel_Model = M('novelrank');
            $rank_where['rank_id'] = $rank_id;
            $rank_where['is_del'] = 0;
            $rank_novel_arr = $rank_novel_Model->where($rank_where)->field('novel_id')->select();
            $novel_arr = [];
            foreach($rank_novel_arr as $key=>$val){
                $novel_arr[] = $val['novel_id'];
            }

            $where['id'] = ['in',$novel_arr];
            $this->assign('rank_id', $rank_id);
        }

        $where['is_del'] = 0;
        $result = $this->getPagination('Novel',$where);
        foreach($result['data'] as $key => $val){
            $result['data'][$key]['class_id'] = M('class')->where(['id'=>$val['class_id']])->getField('class_name');
        }


        $this->assign('novel', $result['data']);
        $this->assign('rows_count', $result['total_rows']);
        $this->assign('page', $result['show']);
        $this->display();
    }

    /**
     * 添加小说页面
     */
    public function add(){
        //分类列表
        $class_list = M('class')->where(['is_del'=>0])->select();
        $this->assign('class_list',$class_list);

        //组合查询分类
        $search_class = M('search_item')->where(['search_class_id'=>4])->select();
        $this->assign('search_class',$search_class);

        //组合查询字数组
        $number_arr = M('search_item')->where(['search_class_id'=>3])->select();
        $this->assign('number_arr',$number_arr);

        $this->display();
    }

    /**
     * 添加小说操作
     */
    public function insert(){
        $Novel_Model = M('novel');
        $data = I('post.data');
        if (!isset($data)) {
            return $this->errorReturn('无效的操作！');
        }

        if($data['title'] == '' || !$data['title']){
            return $this->errorReturn('小说名称不能为空！');
        }elseif($data['author'] == '' || !$data['author']){
            return $this->errorReturn('请填写作者！');
        }elseif($data['intro'] == '' || !$data['intro']){
            return $this->errorReturn('小说描述不能为空！');
        }elseif($data['source_addr'] == '' || !$data['source_addr']){
            return $this->errorReturn('请填写来源名称');
        }elseif($data['source_url'] == '' || !$data['source_url']){
            return $this->errorReturn('请填写来源网址');
        }elseif($data['class_id'] == '' || !$data['class_id']){
            return $this->errorReturn('请选择分类');
        }

        //上传封面
        if($_FILES['cover']['tmp_name']){
            $info = $this->imgUpload('cover');
            if(!$info){
                return $this->errorReturn('封面上传失败请重试！');
            }else{
                $data['cover'] = '/Public/uploads/'.$info['cover']['savepath'].$info['cover']['savename'];
            }
        }

        $data['label'] = str_replace("|",",",$data['label']);
        $data['create_time'] = time();
        $data['update_time'] = time();
        $result = $Novel_Model->add($data);
        if (!$result) {
            return $this->errorReturn('添加失败，稍后请重试！');
        }

        return $this->successReturn('添加小说成功！', U('Novel/index'));
    }


    /**
     * 编辑小说页面
     * @return
     */
    public function edit() {
        if (!isset($_GET['id'])) {
            return $this->error('参数错误，稍后请重试！');
        }

        //分类列表
        $class_list = M('class')->where(['is_del'=>0])->select();
        $this->assign('class_list',$class_list);

        //组合查询分类
        $search_class = M('search_item')->where(['search_class_id'=>4])->select();
        $this->assign('search_class',$search_class);

        //组合查询字数组
        $number_arr = M('search_item')->where(['search_class_id'=>3])->select();
        $this->assign('number_arr',$number_arr);

        //小说详情
        $Novel = M('novel')->getById($_GET['id']);
        $Novel['label'] = str_replace(",","|",$Novel['label']);

        $this->assign('novel', $Novel);

        $this->assign('id',$_GET['id']);
        $this->display();
    }

    /**
     * 更新小说信息
     * @return
     */
    public function update() {
        $Novel_Model = M('novel');
        $data = I('post.data');
        if(!isset($data)){
            return $this->errorReturn('无效的操作！');
        }

        if($data['title'] == '' || !$data['title']){
            return $this->errorReturn('小说名称不能为空！');
        }elseif($data['author'] == '' || !$data['author']){
            return $this->errorReturn('请填写作者！');
        }elseif($data['intro'] == '' || !$data['intro']){
            return $this->errorReturn('小说描述不能为空！');
        }elseif($data['source_addr'] == '' || !$data['source_addr']){
            return $this->errorReturn('请填写来源名称');
        }elseif($data['source_url'] == '' || !$data['source_url']){
            return $this->errorReturn('请填写来源网址');
        }elseif($data['class_id'] == '' || !$data['class_id']){
            return $this->errorReturn('请选择分类');
        }

        $data['label'] = str_replace("|",",",$data['label']);
        $data['update_time'] = time();

        //上传封面
        if($_FILES['cover']['tmp_name']){
            $info = $this->imgUpload('cover');
            if(!$info){
                return $this->errorReturn('封面上传失败请重试！');
            }else{
                $data['cover'] = '/Public/uploads/'.$info['cover']['savepath'].$info['cover']['savename'];
            }
        }

        $result = $Novel_Model->where(['id'=>$data['id']])->save($data);
        if (!$result) {
            return $this->errorReturn('操作失败，请重试！');
        }

        return $this->successReturn('更新小说信息成功！', U('Novel/index'));
    }

    //删除小说
    public function del(){
        $Novel_Model = M('novel');
        $id = I('post.id');
        if(!$id){
            $this->ajaxReturn(['code'=>-1,'msg'=>'参数错误，请重试']);
        }

        $result = $Novel_Model->where(['id'=>$id])->setField('is_del',1);
        if($result){
            $this->ajaxReturn(['code'=>0,'msg'=>'删除成功!']);
        }else{
            $this->ajaxReturn(['code'=>-1,'msg'=>'删除失败，请重试!']);
        }
    }


    /**
     * 章节列表
     * @return
     */
    public function chapter_index() {
        $novel_id = I('get.novel_id');
        $result = $this->getPagination('Chapter',['is_del'=>0,'novel_id'=>$novel_id]);

        $this->assign('novel_id',$novel_id);
        $this->assign('chapter', $result['data']);
        $this->assign('rows_count', $result['total_rows']);
        $this->assign('page', $result['show']);
        $this->display();
    }

    /**
     * 添加章节页面
     */
    public function chapter_add(){
        $novel_id = I('get.novel_id');

        $this->assign('novel_id',$novel_id);
        $this->display();
    }

    /**
     * 添加章节操作
     */
    public function chapter_insert(){
        $Chapter_Model = M('chapter');
        $data = I('post.data');
        if (!isset($data)) {
            return $this->errorReturn('无效的操作！');
        }

        if($data['title'] == '' || !$data['title']){
            return $this->errorReturn('章节名称不能为空！');
        }elseif($data['content'] == '' || !$data['content']){
            return $this->errorReturn('请填写章节内容！');
        }

        //小说对应章节数+1
        $novel_chapter = $Chapter_Model->where(['novel_id'=>$data['novel_id']])->order('id desc')->getField('novel_chapter');
        if(!$novel_chapter){
            $data['novel_chapter'] = 1;
        }else{
            $data['novel_chapter'] = $novel_chapter+1;
        }

        $data['create_time'] = time();
        $data['update_time'] = time();
        $result = $Chapter_Model->add($data);
        if (!$result) {
            return $this->errorReturn('添加失败，稍后请重试！');
        }

        return $this->successReturn('添加章节成功！', U('Novel/chapter_index',["novel_id"=>$data['novel_id']]));
    }


    /**
     * 编辑章节页面
     * @return
     */
    public function chapter_edit() {
        if (!isset($_GET['id'])) {
            return $this->error('参数错误，稍后请重试！');
        }

        //章节详情
        $Chapter = M('chapter')->getById($_GET['id']);
        $this->assign('chapter', $Chapter);

        $this->assign('id',$_GET['id']);
        $this->display();
    }

    /**
     * 更新章节信息
     * @return
     */
    public function chapter_update() {
        $Chapter_Model = M('chapter');
        $data = I('post.data');
        if(!isset($data)){
            return $this->errorReturn('无效的操作！');
        }

        if($data['title'] == '' || !$data['title']){
            return $this->errorReturn('章节名称不能为空！');
        }elseif($data['content'] == '' || !$data['content']){
            return $this->errorReturn('请填写章节内容！');
        }

        $data['update_time'] = time();
        $result = $Chapter_Model->where(['id'=>$data['id']])->save($data);
        if (!$result) {
            return $this->errorReturn('操作失败，请重试！');
        }

        return $this->successReturn('更新章节信息成功！', U('Novel/chapter_index',["novel_id"=>$data['novel_id']]));
    }

    //删除章节
    public function chapter_del(){
        $Chapter_Model = M('chapter');
        $id = I('post.id');
        if(!$id){
            $this->ajaxReturn(['code'=>-1,'msg'=>'参数错误，请重试']);
        }

        $result = $Chapter_Model->where(['id'=>$id])->setField('is_del',1);
        if($result){
            $this->ajaxReturn(['code'=>0,'msg'=>'删除成功!']);
        }else{
            $this->ajaxReturn(['code'=>-1,'msg'=>'删除失败，请重试!']);
        }
    }


    //搜索小说
    public function search_novels(){
        $novel_Model = M('novel');
        $keyword = I('post.keyword');

        $where['title'] = ['like',"%$keyword%"];
        $list = $novel_Model->where($where)->field('id,title')->select();
        if($list){
            $this->ajaxReturn(['code'=>0,'list'=>$list]);
        }else{
            $this->ajaxReturn(['code'=>-1,'msg'=>'没有找到对应小说']);
        }
    }

    /**
     * 组合查询分类列表
     * @return
     */
    public function search_class() {
        $where['is_del'] = 0;
        $result = $this->getPagination('SearchClass',$where);

        $this->assign('list', $result['data']);
        $this->assign('rows_count', $result['total_rows']);
        $this->assign('page', $result['show']);
        $this->display();
    }


    /**
     * 组合查询分类页面
     */
    public function search_class_add(){
        $this->display();
    }

    /**
     * 添加组合查询分类操作
     */
    public function search_class_insert(){
        $Class_Model = M('search_class');
        $data = I('post.class');
        if (!isset($data)) {
            return $this->errorReturn('无效的操作！');
        }

        if($data['name'] == '' || !$data['name']){
            return $this->errorReturn('分类名称不能为空！');
        }

        $result = $Class_Model->add($data);
        if (!$result) {
            return $this->errorReturn('添加失败，稍后请重试！');
        }

        return $this->successReturn('添加分类成功！', U('Novel/search_class'));
    }


    /**
     * 编辑组合查询分类页面
     * @return
     */
    public function search_class_edit() {
        if (!isset($_GET['id'])) {
            return $this->error('参数错误，稍后请重试！');
        }

        $Class = M('search_class')->getById($_GET['id']);

        $this->assign('class', $Class);
        $this->assign('id',$_GET['id']);
        $this->display();
    }

    /**
     * 更新组合查询分类
     * @return
     */
    public function search_class_update() {
        $Class_Model = M('search_class');
        $data = I('post.class');
        if(!isset($data)){
            return $this->errorReturn('无效的操作！');
        }

        if($data['name'] == '' || !$data['name']){
            return $this->errorReturn('分类名称不能为空！');
        }

        $result = $Class_Model->where(['id'=>$data['id']])->save($data);
        if (!$result) {
            return $this->errorReturn('操作失败，请重试！');
        }

        return $this->successReturn('分类名称修改成功！', U('Novel/search_class'));
    }

    //删除组合查询分类
    public function search_class_del(){
        $Class_Model = M('search_class');
        $id = I('post.id');
        if(!$id){
            $this->ajaxReturn(['code'=>-1,'msg'=>'参数错误，请重试']);
        }

        $result = $Class_Model->where(['id'=>$id])->setField('is_del',1);
        if($result){
            $this->ajaxReturn(['code'=>0,'msg'=>'删除成功!']);
        }else{
            $this->ajaxReturn(['code'=>-1,'msg'=>'删除失败，请重试!']);
        }
    }

    /**
     * 组合查询项列表
     * @return
     */
    public function search_item() {
        $class_id = I('get.class_id');
        $result = $this->getPagination('SearchItem',['is_del'=>0,'search_class_id'=>$class_id]);

        $this->assign('class_id',$class_id);
        $this->assign('chapter', $result['data']);
        $this->assign('rows_count', $result['total_rows']);
        $this->assign('page', $result['show']);
        $this->display();
    }

    /**
     * 添加组合查询项页面
     */
    public function search_item_add(){
        $class_id = I('get.class_id');

        $this->assign('class_id',$class_id);
        $this->display();
    }

    /**
     * 添加组合查询项操作
     */
    public function search_item_insert(){
        $item_Model = M('search_item');
        $data = I('post.data');
        if (!isset($data)) {
            return $this->errorReturn('无效的操作！');
        }

        if($data['name'] == '' || !$data['name']){
            return $this->errorReturn('搜索项名称不能为空！');
        }elseif($data['search_class_id'] == '' || !$data['search_class_id']){
            return $this->errorReturn('请选择搜索分类！');
        }elseif($data['field'] == '' || !$data['field']){
            return $this->errorReturn('请填写对应字段值！');
        }

        $result = $item_Model->add($data);
        if (!$result) {
            return $this->errorReturn('添加失败，稍后请重试！');
        }

        return $this->successReturn('添加成功！', U('Novel/search_item',["class_id"=>$data['search_class_id']]));
    }


    /**
     * 编辑组合查询项页面
     * @return
     */
    public function search_item_edit() {
        if (!isset($_GET['id'])) {
            return $this->error('参数错误，稍后请重试！');
        }

        //组合查询项详情
        $search_item = M('search_item')->getById($_GET['id']);
        $this->assign('search_item', $search_item);

        $this->assign('id',$_GET['id']);
        $this->display();
    }

    /**
     * 更新组合查询项
     * @return
     */
    public function search_item_update() {
        $item_Model = M('search_item');
        $data = I('post.data');
        if(!isset($data)){
            return $this->errorReturn('无效的操作！');
        }

        if($data['name'] == '' || !$data['name']){
            return $this->errorReturn('搜索项名称不能为空！');
        }elseif($data['search_class_id'] == '' || !$data['search_class_id']){
            return $this->errorReturn('请选择搜索分类！');
        }elseif($data['field'] == '' || !$data['field']){
            return $this->errorReturn('请填写对应字段值！');
        }


        $result = $item_Model->where(['id'=>$data['id']])->save($data);
        if (!$result) {
            return $this->errorReturn('操作失败，请重试！');
        }

        return $this->successReturn('更新成功！',U('Novel/search_item',["class_id"=>$data['search_class_id']]));
    }

    //删除组合查询项
    public function search_item_del(){
        $item_Model = M('search_item');
        $id = I('post.id');
        if(!$id){
            $this->ajaxReturn(['code'=>-1,'msg'=>'参数错误，请重试']);
        }

        $result = $item_Model->where(['id'=>$id])->setField('is_del',1);
        if($result){
            $this->ajaxReturn(['code'=>0,'msg'=>'删除成功!']);
        }else{
            $this->ajaxReturn(['code'=>-1,'msg'=>'删除失败，请重试!']);
        }
    }


    //上传文件 返回文件路径
    public function upload(){
        //name为text
        if($_FILES['text']['tmp_name']){
            $file_size = $_FILES['text']["size"]; // 文件大小

            if ($file_size > 5000000) {
                $this->ajaxReturn(['code'=>self::FAIL_CODE,'message'=>"文件大小不能超过5M"]);
            }

            $info = CommonController::imgUpload('novel_text');
            if(!$info){
                exit(json_encode(['code'=>self::FAIL_CODE,'message'=>"上传失败，稍后请重试"]));
            }else{
                $text = 'http://'.$_SERVER['HTTP_HOST'].'/Public/uploads/'.$info['text']['savepath'].$info['text']['savename'];
                exit(json_encode(['code'=>0,'message'=>"上传成功",'data'=>$text]));
            }
        }else{
            exit(json_encode(['code'=>-1,'message'=>"上传失败，稍后请重试"]));
        }
    }

    //读取文件 写入数据库
    public function read_text(){
        // $_SERVER["DOCUMENT_ROOT"]，获取当前运行脚本所在文档根目录
//        $filePath = $_SERVER["DOCUMENT_ROOT"] . "/Public/uploads/novel_text/sample1.txt";
        $filePath = I('post.filePath');
        $filePath = $_SERVER["DOCUMENT_ROOT"].strstr($filePath,"/Public/");
//        $filePath = str_replace('http://'.$_SERVER['HTTP_HOST'].'/',WEB_ROOT,I('post.filePath'));

        $result = $this->readText($filePath);
        if($result){
            $this->ajaxReturn(['code'=>0,'message'=>"添加小说成功"]);
        }else{
            $this->ajaxReturn(['code'=>-1,'message'=>"添加失败，稍后请重试"]);
        }
    }

    //文件解析成数组
    public function parse_text(){
        $filePath = I('post.filePath');
        $filePath = $_SERVER["DOCUMENT_ROOT"].strstr($filePath,"/Public/");
        $show_data = CommonController::textToArr($filePath);
        if($show_data){
            $this->ajaxReturn(['code'=>0,'data'=>$show_data,'message'=>'数据解析成功']);
        }else{
            $this->ajaxReturn(['code'=>-1,'message'=>"数据解析失败，稍后请重试"]);
        }
    }

    //添加小说以及小说章节
    public function add_novel(){
        $novel_data = I('post.novel_data');
        $chapter_data = I('post.chapter_data');

        $novel_data['create_time'] = $novel_data['update_time'] = time();
        //写入小说表
        $novel_id = CommonController::addNovel($novel_data);

        //小说章节处理
        if($novel_id){
            foreach($chapter_data as $key=>$val){
                $chapter_data[$key]['novel_id'] = $novel_id;
                $chapter_data[$key]['create_time'] = $chapter_data[$key]['update_time'] = time();
            }

            //写入章节数据库操作
            $result = CommonController::addChapter($chapter_data);
            if($result){
                $this->ajaxReturn(['code'=>0,'message'=>'小说添加成功，请等待审核']);
            }else{
                $this->ajaxReturn(['code'=>-1,'message'=>"小说添加失败，稍后请重试"]);
            }
        }else{
            $this->ajaxReturn(['code'=>-1,'message'=>"小说添加失败，稍后请重试"]);
        }
    }

    //上传文件页面$filename
    public function novel_text(){
        $this->display();
    }

    //批量上传文件页面
    public function novel_zip(){
        $this->display();
    }


    //将文件解压到指定目录并解析
    public function novel_unzip()
    {
        //$filename = $_SERVER["DOCUMENT_ROOT"] . "/Public/uploads/novel_text/5b63aa95ce1b4.zip";
        $filename = I('post.filename');
        $filename = str_replace('http://'.$_SERVER['HTTP_HOST'].'/',WEB_ROOT,$filename);
        $result = CommonController::unzip($filename);
        //小说数据
        $novel_list = [];
        foreach($result as $val){
            $show_data = CommonController::textToArr($val);

            $novel_info = $show_data['novel_info'];
            if($novel_info){
                $novel_list[] = $novel_info;
            }
        }

        if($novel_list){
            $this->ajaxReturn(['code'=>0,'message'=>'解析完成','novel_list'=>$novel_list,'path_list'=>$result]);
        }else{
            $this->ajaxReturn(['code'=>-1,'message'=>"解析失败，稍后请重试"]);
        }

    }


}
